<?php

namespace App\Kuafu\User\Model;

use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\RoleException;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class Role extends BaseModel
{
    use KfSoftDeletes, KfUid;

    public function createdByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'createdByUid');
    }

    public function updatedByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'updatedByUid')->select(['id', 'username']);
    }

    public function userRoleRel()
    {
        return $this->hasMany(UserRoleMapping::class, 'roleId', 'id');
    }

    public function rolePermissionMappingsRel()
    {
        return $this->hasMany(RolePermissionMappings::class, 'roleId', 'id');
    }

    /**
     * 获取职位列表
     *
     * @param $brandId
     * @param $shopId
     * @param $pageSize
     * @param $pageNum
     * @param $params
     * @return array
     */
    public static function getRoleListWithType($brandId, $shopId, $pageSize, $pageNum, $params): array
    {
        $result = Role::query()->where('brandId', $brandId)
                      ->when(attributeGet($params, "name", null), function ($query) use ($params) {
                          return $query->where("name", "like", "%{$params->name}%");
                      })
                      ->when(attributeGet($params, "type", ""), function ($query) use ($params) {
                          return $query->whereIn("type", explode(",", $params->type));
                      })
                      ->when(attributeGet($params, "updatedTimeStart", null), function ($query) use ($params) {
                          return $query->where("updatedAt", ">=", strtotime($params->updatedTimeStart));
                      })
                      ->when(attributeGet($params, "updatedTimeEnd", null), function ($query) use ($params) {
                          return $query->where("updatedAt", "<=", Carbon::createFromDate($params->updatedTimeEnd)->endOfDay()->timestamp);
                      })
                      ->when(attributeGet($params, "updatedByUid", null), function ($query) use ($params) {
                          return $query->where("updatedByUid", $params->updatedByUid);
                      })
                      ->with('updatedByUidRel')
                      ->with('userRoleRel')
                      ->with('rolePermissionMappingsRel')
                      ->select(['id', 'name', 'brandId', 'shopId', 'status', 'updatedAt', 'updatedByUid', 'type'])
                      ->paginate($pageSize, ['*'], $pageName = 'page', $pageNum);

        $itmes = collect($result->items())->each(function ($value) {
            $value->permissionNum = count($value->rolePermissionMappingsRel);
            $value->roleNum       = count($value->userRoleRel);
            $value->updateByName  = $value->updatedByUidRel['username'] ?? "未知操作人";
            unset($value->rolePermissionMappingsRel, $value->userRoleRel, $value->updatedByUidRel);
        })->toArray();

        return [
            'pageNum'  => $result->currentPage(),
            'pageSize' => $result->perPage(),
            'count'    => $result->total(),
            'lists'    => $itmes,
        ];
    }

    /**
     * 根据 Type 返回列表
     *
     * @param $type
     * @return array
     */
    public static function getAllRoleListByType($type)
    {
        $result = Role::query()->where('type', $type)->where('status', 0)->select(['id', 'name', 'type'])->get()
                      ->toArray();

        return $result;
    }

    /**
     * 添加职位
     *
     * @param Request $request
     * @return int
     * @throws RoleException
     */
    public static function addRole(array $addData): int
    {
        $role          = new Role();
        $role->name    = $addData['name'];
        $role->brandId = $addData['brandId'];
        $role->shopId  = $addData['shopId'] ?? 0;
        $role->status  = $addData['status'] ?? 0;
        $role->type    = $addData['type'];

        if (!$role->save()) {
            throw new RoleException(BaseCodeEnum::ERR_DB_ERROR);
        }

        return $role->id;
    }

    /**
     * 编辑职位
     *
     * @param Request $request
     * @param $roleId
     * @return array|bool
     * @throws RoleException
     */
    public static function editRole(Request $request, $roleId)
    {
        $obj = Role::query()->find($roleId);

        if (empty($obj)) {
            return self::returnData(UserCodeEnum::ERR_PMS_ROLE_PARAM_ROLE_ID);
        }

        $obj->name = $request->post('name');

        if (!$obj->save()) {
            throw new RoleException(BaseCodeEnum::ERR_DB_ERROR);
        }

        return true;
    }


    /**
     * 根据角色 Id 获取详情
     *
     * @param $ids
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getRoleListByIds($ids)
    {
        return self::query()->whereIn('id', $ids)->get();
    }


}
